﻿using AntdUI;
using DataCollection.Core.Models;
using DataCollection.Infrastructure;
using DataCollection.WinForm;
using DataCollection.WinForm.Forms;
using DataCollection.WinForm.ViewModel;
using Dm;
using Dm.util;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Data;
using System.IO;
using Masuit.Tools;
using Masuit.Tools.Database;
using ScottPlot;
using SkiaSharp;
using SqlSugar;
using System.Reflection;
using DocumentFormat.OpenXml;

namespace DataCollection
{
    public partial class IndexForm : DCBaseForm
    {
        #region 属性

        /// <summary>
        /// 数据库是否可用
        /// </summary>
        private bool DBEnable = false;

        private CollectionViewModel collectionViewModel = new CollectionViewModel();

        readonly private SystemSetModel SystemSetModelServices = Singleton.Instance.SetModel;

        readonly private BroadcastServices Broadcast = new BroadcastServices();

        private HistoryModel historyModel = new HistoryModel();

        /// <summary>
        /// 悬浮快捷按钮
        /// </summary>
        private Form? FloatButton = null;
        /// <summary>
        /// 悬浮按钮显示状态
        /// </summary>
        private bool ShowFloatButton = false;

        /// <summary>
        /// 开始采集
        /// </summary>
        private bool StartCollection = false;

        /// <summary>
        /// 完成采集
        /// </summary>
        private bool FinishCollection = false;

        /// <summary>
        /// 保留小数位数
        /// </summary>
        readonly private int Decimal = 4;

        /// <summary>
        /// 总时间
        /// </summary>
        private long TotalTime = 0;

        //开始时间
        private DateTime StartTime;

        //结束时间
        private DateTime EndTime;

        /// <summary>
        /// 选择的试压工程
        /// </summary>
        public ProjectItem? SelectProjectItem;

        /// <summary>
        /// 选择的试压模板
        /// </summary>
        public TemplateModel? SelectTemplateModel;

        /// <summary>
        /// 需要播报的阶段信息
        /// </summary>
        private string StageMessage;

        /// <summary>
        /// 播报数据
        /// </summary>
        private bool EnableBroadcastData = false;

        #endregion

        #region 实时数据属性

        /// <summary>
        /// 允许采集
        /// </summary>
        public bool EnableCollection;

        /// <summary>
        /// 主压力
        /// </summary>
        public double MainPressure;

        /// <summary>
        /// 近端介质温度
        /// </summary>
        public double MainMediumTemperature;

        /// <summary>
        /// 近端环境温度
        /// </summary>
        public double MainEnviromentTemperature;

        /// <summary>
        /// 主电池
        /// </summary>
        public double MainBattery;

        /// <summary>
        /// 远端压力
        /// </summary>
        public double RemotePressure;

        /// <summary>
        /// 远端介质温度
        /// </summary>
        public double RemoteMediumTemperature;

        /// <summary>
        /// 远端电池
        /// </summary>
        public double RemoteBattery;


        #endregion

        #region 计时器属性

        /// <summary>总计时器
        /// 
        /// </summary>
        private System.Timers.Timer TotalTimer = new System.Timers.Timer();

        /// <summary>采集计时器
        /// 
        /// </summary>
        private System.Timers.Timer CollectionTimer = new System.Timers.Timer();

        /// <summary> 开始采集计时器
        /// 
        /// </summary>
        private System.Timers.Timer CollectStateTimer = new System.Timers.Timer();

        /// <summary> 起步计时器
        /// 
        /// </summary>
        private System.Timers.Timer StartStageTimer = new System.Timers.Timer();

        /// <summary> 当前阶段计时器
        /// 
        /// </summary>
        private System.Timers.Timer StageTimer = new System.Timers.Timer();

        /// <summary>
        /// 播报数据
        /// </summary>
        private System.Timers.Timer BroadcastDataTimer = new System.Timers.Timer();

        #endregion

        #region 试压起步属性

        /// <summary> 
        /// 起步阶段压力
        /// </summary>
        double StartStagePressure = -1;

        /// <summary> 
        /// 起步阶段压力上限
        /// </summary>
        double StartStagePressureMax = -1;

        /// <summary> 
        /// 起步阶段压力下限
        /// </summary>
        double StartStagePressureMin = -1;

        /// <summary>起步阶段总时间
        /// 单位s
        /// </summary>
        int StartStageTimeInterval = 10;

        /// <summary>当前步阶段剩余时间
        /// 单位s
        /// </summary>
        int StartStageTime = 10;

        /// <summary>
        /// 开始起步稳压
        /// </summary>
        bool StartStageHolding = false;

        /// <summary>
        /// 采集点列表
        /// </summary>
        private List<double> PointList = new List<double>();

        #endregion

        #region 保持阶段属性
        /// <summary> 保持阶段压力
        /// 
        /// </summary>
        double HoldingStagePressure;

        /// <summary> 保持阶段压力上限
        /// 
        /// </summary>
        double HoldingStagePressureMax = 0;

        /// <summary> 保持阶段压力下限
        /// 
        /// </summary>
        double HoldingStagePressureMin = 0;

        /// <summary>
        /// 允许保持阶段
        /// </summary>
        bool EnableHoldingStage = false;

        /// <summary>
        /// 当前阶段试压结果
        /// </summary>
        bool StageResult = false;

        /// <summary> 保持阶段压力错误次数
        /// 
        /// </summary>
        int HoldStagePressureErrorTimes = 0;

        /// <summary> 保持阶段压差错误次数
        /// 
        /// </summary>
        int HoldStagePressureDiffenceErrorTimes = 0;
        #endregion

        #region 试压属性

        /// <summary>
        /// 阶段List
        /// </summary>
        List<string> StageList = new List<string>();

        /// <summary>
        /// 阶段数量
        /// </summary>
        int StageCount = -1;

        /// <summary>
        /// 结果数组
        /// </summary>
        List<string> ResultList = new List<string>();

        string CurrentStage = string.Empty;

        /// <summary>
        /// 当前阶段总时间
        /// </summary>
        long StageTotalTime = 0;

        /// <summary>
        /// 当前阶段剩余时间
        /// </summary>
        private string StageSurplusTimeString = string.Empty;

        /// <summary>
        /// 压力差值
        /// </summary>
        private double PressureDifference = 0;

        /// <summary>
        /// 压差错误次数
        /// </summary>
        private double PressureDifferenceErrorTimes  = 0;
        #endregion

        #region 曲线属性

        ScottPlot.Plottables.DataLogger MPressureLogger;

        ScottPlot.Plottables.DataLogger RPressureLogger;

        ScottPlot.Plottables.DataLogger MTemperatureLogger;

        private System.Timers.Timer ScottPlotTimer = new() { Interval = 1100, Enabled = true };

        private System.Timers.Timer UpdatePlotTimer = new() { Interval = 1100, Enabled = true };

        /// <summary>
        /// 根地址
        /// </summary>
        readonly private string ReportRootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CollectReport");

        /// <summary>
        /// 温度曲线图片地址
        /// </summary>
        /// 
        private string TemplatureImagePath = string.Empty;

        /// <summary>
        /// 压力曲线图片地址
        /// </summary>
        /// 
        private string PressureImagePath = string.Empty;

        #endregion

        #region 固定方法

        /// <summary>
        /// 数据库错误
        /// </summary>
        /// <param name="showNotifaction">是否显示通知</param>
        private void DBError(bool showNotifaction = true)
        {
            string msg = "连接数据库错误";
            if (showNotifaction)
            {
                ErrorNotification(msg);
            }
            AlertMessage(msg);
        }

        /// <summary>
        /// 底部滚动提示信息 
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="type"></param>
        private void AlertMessage(string msg)
        {
            this.Invoke(new System.Windows.Forms.MethodInvoker(delegate
            {
                Alert1.Text = msg;
            }));
        }

        /// <summary>
        /// 实时数据Label
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private AntdUI.Label? DataLabel(string name)
        {
            if (name.Length <= 0)
            {
                return null;
            }
            System.Windows.Forms.Control[] cols = DataPanel.Controls.Find(name, true);
            if (cols.Length > 0)
            {
                System.Windows.Forms.Control col = cols[0];
                AntdUI.Label? label = col as AntdUI.Label;
                return label;
            }
            else
            {
                cols = GridPanel2.Controls.Find(name, true);
                if (cols.Length > 0)
                {
                    System.Windows.Forms.Control col = cols[0];
                    AntdUI.Label? label = col as AntdUI.Label;
                    return label;
                }
                else
                {
                    return null;
                }
            }

        }

        private AntdUI.Battery? Battery(string name)
        {
            if (name.Length <= 0)
            {
                return null;
            }
            System.Windows.Forms.Control[] cols = DataPanel.Controls.Find(name, true);
            if (cols.Length > 0)
            {
                System.Windows.Forms.Control col = cols[0];
                AntdUI.Battery? obj = col as AntdUI.Battery;
                return obj;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 阶段结果Label
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private AntdUI.Label? StageResultLabel(string name)
        {
            name = name + "ResultLabel";
            System.Windows.Forms.Control col = TimePanel.Controls.Find(name, true)[0];
            AntdUI.Label? label = col as AntdUI.Label;
            return label;
        }

        /// <summary>
        /// 计时器
        /// </summary>
        /// <returns></returns>
        private System.Timers.Timer CollectTimer()
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.AutoReset = true;//是否重复执行
            return timer;
        }

        /// <summary>
        /// 更新当前阶段的试压状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="res"></param>
        private void UpdateCurrentStageResult(string id, bool res)
        {
            AntdUI.Label? label = StageResultLabel(id);
            if (label != null)
            {
                if (res == true)
                {
                    label.BadgeBack = System.Drawing.Color.Green;
                    label.Badge = "完成";
                }
                else
                {
                    label.BadgeBack = System.Drawing.Color.Green;
                    label.Badge = "完成";
                }
            }
        }

        /// <summary>
        /// 当前时间
        /// </summary>
        private void NowTime() 
        {
            DateTime time = DateTime.Now;
            TimeLabel.Text = time.ToString("HH:mm:ss");
            DateLabel.Text = time.ToString("MM-dd");
            WeekLabel.Text = Util.TodayWeek();
        }


        private void RestPlot()
        {
            if (MPressureLogger.HasNewData)
            {
                MPressureLogger.Clear();
                RPressureLogger.Clear();
                MTemperatureLogger.Clear();
                FormsPlot1.Plot.Clear();
            }
            this.Invoke(new Action(() =>
            {
                FormsPlot1.Refresh();
            }));
        }

        /// <summary>
        /// 配置曲线
        /// </summary>
        private void SetupPlot()
        {
            ScottPlot.Plot myPlot = FormsPlot1.Plot;
            myPlot.Font.Set(SKFontManager.Default.MatchCharacter('汉').FamilyName);
            var axis = myPlot.Axes.DateTimeTicksBottom();
            var tickGen = (ScottPlot.TickGenerators.DateTimeAutomatic)axis.TickGenerator;
            tickGen.LabelFormatter = PlotBottomFormatter;

            MPressureLogger = myPlot.Add.DataLogger();
            MPressureLogger.ViewFull();
            MPressureLogger.LineWidth = 2.0f;
            MPressureLogger.LineColor = ScottPlot.Color.FromHex("#FF0000");
            MPressureLogger.LegendText = "近端压力";

            RPressureLogger = myPlot.Add.DataLogger();
            RPressureLogger.ViewFull();
            RPressureLogger.LineWidth = 2.0f;
            RPressureLogger.LineColor = ScottPlot.Color.FromHex("#8B4513");
            RPressureLogger.LegendText = "远端压力";

            ScottPlot.Plot myPlot2 = FormsPlot2.Plot;
            myPlot2.Font.Set(SKFontManager.Default.MatchCharacter('汉').FamilyName);
            var axis2 = myPlot2.Axes.DateTimeTicksBottom();
            var tickGen2 = (ScottPlot.TickGenerators.DateTimeAutomatic)axis2.TickGenerator;
            tickGen2.LabelFormatter = PlotBottomFormatter;

            MTemperatureLogger = myPlot2.Add.DataLogger();
            MTemperatureLogger.ViewFull();
            MTemperatureLogger.LineWidth = 2.0f;
            MTemperatureLogger.LineColor = ScottPlot.Color.FromHex("#1C6CC9");
            MTemperatureLogger.LegendText = "环境温度";

            myPlot.ScaleFactor = AntdUI.Config.Dpi;

            myPlot.Axes.SetLimitsY(0, 3);
            PixelPadding padding = new(30, 40, 30, 20);
            myPlot.Layout.Fixed(padding);

            myPlot.Legend.IsVisible = true;
            myPlot.Legend.Alignment = ScottPlot.Alignment.UpperLeft;
            myPlot.Legend.Orientation = ScottPlot.Orientation.Horizontal;

            // tell the left axis to use our custom tick generator
            //myPlot.Axes.Left.TickGenerator = new ScottPlot.TickGenerators.NumericFixedInterval(0.5);
            ScottPlot.TickGenerators.NumericAutomatic tickGenY = new();
            tickGenY.TargetTickCount = 10;
            myPlot.Axes.Left.TickGenerator = tickGenY;

            var now = DateTime.Now;
            myPlot.Axes.SetLimitsX(now.ToOADate(), now.AddMinutes(5).ToOADate());

       
            myPlot2.ScaleFactor = AntdUI.Config.Dpi;
            myPlot2.Axes.SetLimitsY(0, 42);
            myPlot2.Layout.Fixed(padding);
            myPlot2.Legend.IsVisible = true;
            myPlot2.Legend.Alignment = ScottPlot.Alignment.UpperLeft;
            myPlot2.Legend.Orientation = ScottPlot.Orientation.Horizontal;
            myPlot2.Axes.SetLimitsX(now.ToOADate(), now.AddMinutes(5).ToOADate());
            myPlot2.Axes.Left.TickGenerator = new ScottPlot.TickGenerators.NumericFixedInterval(5);

            this.Invoke(new Action(() =>
            {
                FormsPlot1.Refresh();
                FormsPlot2.Refresh();
            }));
        }

        /// <summary>
        /// 更新曲线范围，添加指示横线
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        private void UpdatePlotRange(double min, double max)
        {
            FormsPlot1.Plot.Add.HorizontalLine(min,2, ScottPlot.Color.FromHex("#3CB371"));
            FormsPlot1.Plot.Add.HorizontalLine(max,2, ScottPlot.Color.FromHex("#FFA500"));
            
            this.Invoke(new Action(() =>
            {
                FormsPlot1.Refresh();
            }));
        }
        /// <summary>
        /// 曲线自定义X轴
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        static string PlotBottomFormatter(DateTime dt)
        {
            bool isMidnight = dt is { Hour: 0, Minute: 0, Second: 0 };
            return isMidnight
                ? DateOnly.FromDateTime(dt).ToString()
                : TimeOnly.FromDateTime(dt).ToString("HH:mm:ss");
        }

        /// <summary>
        /// 格式化数据
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private int ParaseValue(double value)
        {
            int res = 0;
            if (value < 5)
            {
                value = 5;
            }
            else if (value < 10)
            {
                res = 10;
            }
            else
            {
                int tmp = (int)(value / 10);
                res = (tmp + 1) * 10;
            }

            return res;
        }

        /// <summary>
        /// 更新采集的数据，广播给移动网页
        /// </summary>
        private void UpdateCollectionDict()
        {
            Singleton.Instance.CollectData["mPressure"] = MainPressure.toString();
            Singleton.Instance.CollectData["mEnvironmentTemperature"] = MainEnviromentTemperature.toString();
            Singleton.Instance.CollectData["mBattery"] = MainBattery.toString();
            Singleton.Instance.CollectData["rPressure"] = RemotePressure.toString();
            Singleton.Instance.CollectData["rEnvironmentTemperature"] = "0";
            Singleton.Instance.CollectData["rBattery"] =RemoteBattery.toString();
        }

        /// <summary>
        /// 设置定时器
        /// </summary>
        private void SetupTimer()
        {
            TotalTimer = CollectTimer();
            TotalTimer.Elapsed += MainTime;

            CollectionTimer = CollectTimer();
            CollectionTimer.Elapsed += ReadRegister;

            CollectStateTimer = CollectTimer();
            CollectStateTimer.Interval = 1000;
            CollectStateTimer.Elapsed += CollecttionState;

            StartStageTimer = CollectTimer();
            StartStageTimer.Elapsed += CheckStartStage;

            StageTimer = CollectTimer();
            StageTimer.Elapsed += CheckStage;

            ScottPlotTimer = CollectTimer();
            ScottPlotTimer.Elapsed += ScottPlotAdd;

            UpdatePlotTimer = CollectTimer();
            UpdatePlotTimer.Elapsed += UpdateScottPlot;

            BroadcastDataTimer = CollectTimer();
            BroadcastDataTimer.Elapsed += BroadcastData;
            if (SystemSetModelServices.BroadcastInterval > 0)
            {
                BroadcastDataTimer.Interval = SystemSetModelServices.BroadcastInterval * 60 * 1000;
            }
        }

        /// <summary>
        /// 确定开始
        /// </summary>
        private void ConfirmStart()
        {
            string log = string.Format("起步：{0}m，{1}个点", SystemSetModelServices.HoldingTime, SystemSetModelServices.HoldingPointCount);
            Log.Debug(log);
            ReloadStageResultLabel();
            UpdateStartStageInfo(StageList[0]);
            Broadcast.Broadcast("设备启动，请注意安全。");
            StartCollection = true;
            CollectionTimer.Start();
            StartStageTimer.Start();
            BroadcastDataTimer.Start();
            ScottPlotTimer.Start();
            UpdatePlotTimer.Start();
            AlertMessage("数据采集中");
        }

        /// <summary>
        /// 确定停止
        /// </summary>
        private void ConfirmStop()
        {
            StartCollection = false;
            FinishCollection = true;
            ScottPlotTimer.Stop();
            UpdatePlotTimer.Stop();
            BroadcastDataTimer.Stop();
            CollectionTimer.Stop();
            StartStageTimer.Stop();
            StageTimer.Stop();

            EndTime = DateTime.Now;
            historyModel.EndTime = Util.Timestamp(EndTime);
            historyModel.TotalTime = historyModel.EndTime - historyModel.StartTime;
            historyModel.Update();

            ReStartTimer();

            //清理开始采集标识
            StartCollection = false;

            ///阶段总时长
            StageTotalTime = 0;

            ///累计总时长
            TotalTime = 0;

            //错误统计次数清0
            HoldStagePressureDiffenceErrorTimes = 0;
            HoldStagePressureErrorTimes = 0;

            ///取样点数组
            PointList.Clear();

            ///阶段数组
            StageList.Clear();
        }

        private string StageString(string stage)
        {
            string stageString = "";
            if (stage == "first")
            {
                stageString = "第一阶段";
            }
            else if (stage == "second")
            {
                stageString = "第二阶段";
            }
            else if (stage == "third")
            {
                stageString = "第三阶段";
            }
            else if (stage == "intensity")
            {
                stageString = "强度段";
            }
            else if (stage == "rigor")
            {
                stageString = "严密段";
            }
            return stageString;
        }

        /// <summary>
        /// 重载阶段结果
        /// </summary>
        private void ReloadStageResultLabel()
        {
            List<string> list = ["FirstStage", "SecondStage", "ThirdStage", "IntensityStage", "RigorStage"];

            foreach (string name in list)
            {
                AntdUI.Label? label = StageResultLabel(name);
                if (label != null)
                {
                    label.Badge = "";
                    label.BadgeBack = SystemColors.ActiveCaption;
                }
            }
        }

        #endregion

        #region 自定义方法

        /// <summary>
        /// 加载菜单
        /// </summary>
        private void SetupMenu()
        {
            var menuItems = Util.MenuItems;

            foreach (var rootItem in menuItems)
            {
                var rootMenu = new AntdUI.MenuItem
                {
                    Text = rootItem.Text,
                    IconSvg = rootItem.IconSvg,
                    Tag = rootItem.Tag,
                };
                DCMenu.Items.Add(rootMenu);
            }
        }

        private bool CheckStartCollection()
        {
            if (StartCollection)
            {
                WarnNotification("数据采集中...");
            }
            return StartCollection;
        }

        /// <summary>
        /// 设置悬浮按钮
        /// </summary>
        private void SetupFloatButton()
        {
            if (ShowFloatButton)
            {
                FloatButton?.Close();
            }
            else
            {
                FloatButton?.Close();
                FloatButton.Config config = new AntdUI.FloatButton.Config(this,
                                                    new AntdUI.FloatButton.ConfigBtn[] {
                                                       new AntdUI.FloatButton.ConfigBtn("StartCollection", "FundProjectionScreenOutlined", true){
                                                            Tooltip = "开始采集",
                                                            Type= AntdUI.TTypeMini.Success
                                                         },
                                                       new AntdUI.FloatButton.ConfigBtn("StopCollection", "PoweroffOutlined", true){
                                                            Tooltip = "停止采集",
                                                            Round = false,
                                                            Type= AntdUI.TTypeMini.Warn
                                                        },
                                                        new AntdUI.FloatButton.ConfigBtn("SelectProject", "ProfileOutlined", true){
                                                            Tooltip = "选择工程",
                                                            Round = false,
                                                            Type= AntdUI.TTypeMini.Primary
                                                        },
                                                        new AntdUI.FloatButton.ConfigBtn("TestFan", "PlayCircleOutlined", true){
                                                            Tooltip = "远程操作",
                                                            Round = false,
                                                            Type= AntdUI.TTypeMini.Primary
                                                        }
                                                    },
                                                    btn =>
                                                    {
                                                        if (btn.Name == "StartCollection")
                                                        {
                                                            if (!DBEnable)
                                                            {
                                                                DBError();
                                                                return;
                                                            }
                                                            if (CheckStartCollection())
                                                            {
                                                                return;
                                                            }

                                                            if (SelectProjectItem == null)
                                                            {
                                                                string msg = "请选择试压工程";
                                                                Error(msg);
                                                                Broadcast.Broadcast(msg);
                                                                return;
                                                            }

                                                            if (StageList.Count == 0)
                                                            {
                                                                string msg = "当前无试压阶段，请重新选择工程";
                                                                Error(msg);
                                                                Broadcast.Broadcast(msg);
                                                                return;
                                                            }

                                                            AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", "点击确定开始采集")
                                                            {
                                                                OnOk = config =>
                                                                {
                                                                    historyModel = new HistoryModel();
                                                                    historyModel.Number = DateTimeOffset.Now.ToUnixTimeSeconds();
                                                                    historyModel.ProjectNumber = long.Parse(SelectProjectItem.Number);
                                                                    historyModel.ProjectName = SelectProjectItem.Name;
                                                                    StartTime = DateTime.Now;
                                                                    historyModel.StartTime = Util.Timestamp(StartTime);
                                                                    int res = historyModel.Add();
                                                                    if (res == 1)
                                                                    {
                                                                        CollectStateTimer.Start();
                                                                    }
                                                                    else
                                                                    {
                                                                        Error("试压记录创建失败，请重试！");
                                                                    }
                                                                    
                                                                    return true;
                                                                },
                                                            });
                                                        }
                                                        else if (btn.Name == "StopCollection")
                                                        {
                                                            if (!StartCollection)
                                                            {
                                                                AntdUI.Notification.warn(this, "友情提示", "未开始采集", autoClose: 3, align: TAlignFrom.TR);
                                                                return;
                                                            }
                                                            AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", "您确定要停止采集吗？")
                                                            {
                                                                OnOk = config =>
                                                                {
                                                                    ConfirmStop();
                                                                    return true;
                                                                },
                                                            });
                                                        }
                                                        else if (btn.Name == "SelectProject")
                                                        {
                                                            if (CheckStartCollection())
                                                            {
                                                                return;
                                                            }
                                                            ManageProjectForm frm = new ManageProjectForm();
                                                            frm.Type = 1;
                                                            frm.Owner = this;
                                                            frm.ShowDialog();
                                                        }
                                                        else if (btn.Name == "TestFan")
                                                        {
                                                            QRCoderForm form = new QRCoderForm();
                                                            form.ShowDialog();
                                                        }
                                                    }
                                                 );
                FloatButton = AntdUI.FloatButton.open(config);
                ShowFloatButton = true;
            }
        }
        #endregion

        #region 系统事件
        public IndexForm()
        {
            InitializeComponent();
            FullScreen = true;
            SetupTimer();
            Broadcast.Setup();
        }

        private void IndexForm_Load(object sender, EventArgs e)
        {
            NowTime();
            SetupMenu();
            SetupFloatButton();
            DCSpin(this, "检查数据库...", (action) =>
            {
                DBEnable = SqlSugarHelper.DBEnable;
                if (!DBEnable)
                {
                    DBError();
                }
                else
                {
                    collectionViewModel.Setup();
                    collectionViewModel.ReadRegisterErrorEvent += ReadRegisterError;
                    collectionViewModel.PointValueErrorEvent += PointValueError;
                    StartStageTimeInterval = SystemSetModelServices.HoldingTime * 60;
                    if (SystemSetModelServices.Development == 1)
                    {
                        StartStageTimeInterval = StartStageTimeInterval / 4;
                    }
                    StartStageTime = StartStageTimeInterval;
                    TotalTimer.Start();
                }
            }, null, () => {
                Singleton.Instance.FormsPlotWidth = FormsPlot1.Width;
                Singleton.Instance.FormsPlotHeight = FormsPlot1.Height;
                SetupPlot();
            });
        }

        private void ReadRegisterError(string msg, Exception ex)
        {
            CollectionStateLabel.Text = "当前状态：异常";
            AlertMessage(msg);
        }

        private void PointValueError(string msg) 
        {
            AlertMessage(msg);
        }

        #endregion

        #region 点击菜单
        private void DCMenu_SelectChanged(object sender, AntdUI.MenuSelectEventArgs e)
        {
            if (!DBEnable)
            {
                DBError(true);
                return;
            }
            if (e.Value.Tag != null)
            {
                string tag = (string)e.Value.Tag;
                if (tag == "FloatButton")
                {

                }
                // 如果不存在相应的 TabPage，创建新的
                DCBaseForm? form = null;
                switch (tag)
                {
                    case "DeviceManage":
                        form = new ManageDeviceForm();
                        break;
                    case "FloatButton":

                        break;
                    case "TemplateManage":
                        form = new ManageTemplateForm();
                        break;
                    case "ProjectManage":
                        form = new ManageProjectForm();
                        break;
                    case "FormManage":
                        form = new ManageFormPointForm();
                        break;
                    case "Report":
                        if (CheckStartCollection())
                        {
                            return;
                        }
                        if (!FinishCollection)
                        {
                            Error("试压未完成，无法生成报告");
                            return;
                        }
                        SavedImageInfo templatureInfo = FormsPlot2.Plot.SavePng(TemplatureImagePath, FormsPlot1.Width, FormsPlot1.Height);
                        SavedImageInfo pressureInfo = FormsPlot1.Plot.SavePng(PressureImagePath, FormsPlot1.Width, FormsPlot1.Height);
                        ReportForm frm = new ReportForm();
                        if (SelectProjectItem is not null)
                        {
                            frm.SelectedProjectItem = SelectProjectItem;
                        }
                        if (SelectTemplateModel is not null)
                        {
                            frm.SelectedTemplateModel = SelectTemplateModel;
                        }

                        if (historyModel != null)
                        {
                            frm.SelectedHistoryModel = historyModel;
                        }
                        frm.PressureImagePath = PressureImagePath;
                        frm.TemperatureImagePath = TemplatureImagePath;
                        form = frm;
                        break;
                    case "History":
                        form = new HistoryForm();
                        break;
                    case "SystemSet":
                        SystemSetForm frm2 = new SystemSetForm();
                        frm2.StartCollection = StartCollection;
                        frm2.Owner = this;
                        form = frm2;
                        break;
                }


                if (form != null)
                {
                    if (tag != "SystemSet")
                    {
                        if (CheckStartCollection())
                        {
                            return;
                        }
                    }
                    form.ShowDialog();
                }
            }
        }
        #endregion

        #region 加载工程模板信息

        public void LoadProjectInfo()
        {
            if (SelectProjectItem is not null)
            {
                ProjectNameLabel.Text = SelectProjectItem.Name;
                StakeMarkLabel.Text = SelectProjectItem.StakeMark;
                PipeLengthLabel.Text = SelectProjectItem.PipeLength;
                DesignPressureLabel.Text = SelectProjectItem.DesignPressure.ToString();
                MediumLabel.Text = SelectProjectItem.Medium;
                PipeSpecificationLabel.Text = SelectProjectItem.PipeSpecification;
                string templateId = SelectProjectItem.TemplateID;
                LoadTemplateInfo(templateId);
                TemplatureImagePath = string.Format("{0}\\{1}_templature.png", ReportRootPath, SelectProjectItem.Number);
                PressureImagePath = string.Format("{0}\\{1}_pressure.png", ReportRootPath, SelectProjectItem.Number);
                FinishCollection = false;
            }
        }
        /// <summary>
        /// 加载试压模板信息
        /// </summary>
        private void LoadTemplateInfo(string id)
        {
            Dictionary<string, object> where = new Dictionary<string, object>();
            if (SelectProjectItem is not null)
            {
                where["number"] = SelectProjectItem.TemplateID;
            }
            List<TemplateModel>list = TemplateModel.List(where);
           
            if (list.Count <= 0)
            {
                AntdUI.Notification.warn(this, "友情提示", "试压模板信息异常，请重新选择试压工程", autoClose: 10, align: TAlignFrom.TR);
                Log.Error(string.Format("{0}工程选取的【{1}】试压模板信息不存在", SelectProjectItem.Name, id));
                return;
            }
            SelectTemplateModel = list.First();
            double pressure = SelectTemplateModel.FirstStagePressure;
            List<double> pressureList = new List<double>();
            if (pressure > 0)
            {
                StageList.Add("first");
                if (StartStagePressure == -1)
                {
                    StartStagePressure = Math.Round(pressure, Decimal);
                }
                pressureList.Add(pressure);
            }

            pressure = SelectTemplateModel.SecondStagePressure;
            if (pressure > 0)
            {
                StageList.Add("second");
                if (StartStagePressure == -1)
                {
                    StartStagePressure = Math.Round(pressure, Decimal);
                }
                pressureList.Add(pressure);
            }

            pressure = SelectTemplateModel.ThirdStagePressure;
            if (pressure > 0)
            {
                StageList.Add("third");
                if (StartStagePressure == -1)
                {
                    StartStagePressure = Math.Round(pressure, Decimal);
                }
                pressureList.Add(pressure);
            }

            pressure = SelectTemplateModel.IntensityStagePressure;
            if (pressure > 0)
            {
                StageList.Add("intensity");
                if (StartStagePressure == -1)
                {
                    StartStagePressure = Math.Round(pressure, Decimal);
                }
                pressureList.Add(pressure);
            }

            pressure = SelectTemplateModel.RigorStagePressure;
            if (pressure > 0)
            {
                StageList.Add("rigor");
                if (StartStagePressure == -1)
                {
                    StartStagePressure = Math.Round(pressure, Decimal);
                }
                pressureList.Add(pressure);
            }

            StageCount = StageList.Count;

            pressureList = pressureList.OrderByDescending(n => n).ToList();
            double min = 0;
            double max = 0;
            if (pressureList.Count >= 2)
            {
                max = pressureList.First();
                min = pressureList.Last();
            }
            else
            {
                max = pressureList.First();
            }

            RestPlot();

            if (!(min <= 0 && max <= 0))
            {
                UpdatePlotRange(min, max);
            }
        }

        #endregion

        #region 更新起步阶段信息
        private void UpdateStartStageInfo(string stage)
        {
            if (SelectTemplateModel is not null)
            {
                CurrentStage = stage;
                string stageString = StageString(stage);
                CurrentStageLabel.Text = stageString;
                double multiple = 1;
                int tmp = 60;
                if (SystemSetModelServices.Development == 1)
                {
                    tmp = 1;
                }
                int time = 0;
                string unit = string.Empty;
                if (stage == "first")
                {
                    StartStagePressure = SelectTemplateModel.FirstStagePressure;
                    unit = SelectTemplateModel.FirstStageTimeUnit;
                    if (SelectTemplateModel.FirstStageTimeUnit == "小时")
                    {
                        multiple = tmp;
                    }
                    time = SelectTemplateModel.FirstStageTime;
                }
                else if (stage == "second")
                {
                    StartStagePressure = SelectTemplateModel.SecondStagePressure;
                    unit = SelectTemplateModel.SecondStageTimeUnit;
                    if (SelectTemplateModel.SecondStageTimeUnit == "小时")
                    {
                        multiple = tmp;
                    }
                    time = SelectTemplateModel.SecondStageTime;
                }
                else if (stage == "third")
                {
                    StartStagePressure = SelectTemplateModel.ThirdStagePressure;
                    unit = SelectTemplateModel.ThirdStageTimeUnit;
                    if (SelectTemplateModel.ThirdStageTimeUnit == "小时")
                    {
                        multiple = tmp;
                    }
                    time = SelectTemplateModel.ThirdStageTime;
                }
                else if (stage == "intensity")
                {
                    StartStagePressure = SelectTemplateModel.IntensityStagePressure;
                    unit = SelectTemplateModel.IntensityStageTimeUnit;
                    if (SelectTemplateModel.IntensityStageTimeUnit == "小时")
                    {
                        multiple = tmp;
                    }
                    time = SelectTemplateModel.IntensityStageTime;
                }
                else if (stage == "rigor")
                {
                    StartStagePressure = SelectTemplateModel.RigorStagePressure;
                    unit = SelectTemplateModel.RigorStageTimeUnit;
                    if (SelectTemplateModel.RigorStageTimeUnit == "小时")
                    {
                        multiple = tmp;
                    }
                    time = SelectTemplateModel.RigorStageTime;
                }

                StartStagePressureMax = Math.Round(StartStagePressure * (1 + (SelectTemplateModel.ErrorRange / 100.0f)), 3);
                //StartStagePressureMin = Math.Round(StartStagePressure * (1 - (SelectTemplateModel.ErrorRange / 100.0f)), 3);
                StartStagePressureMin = StartStagePressure;
                StageTotalTime = (long)(time * tmp * multiple);
                StageSurplusTimeLabel.Text = Util.SecondToHMS(StageTotalTime);
                PressureDifferenceErrorTimes = Math.Ceiling(StageTotalTime * (5.0 / 100));
                StageMessage = string.Format("{0}{1}{2}开始倒计时", stageString, time, unit);
                PressureStandardLabel.Text = string.Format("{0}：{1}MPa-{2}MPa", StageString(CurrentStage), StartStagePressureMin, StartStagePressureMax);
                string log = string.Format("【{0}】,起步基准：【{1}】【{2}-{3}】| 异常限制【{4}】次", StageString(CurrentStage), StartStagePressure, StartStagePressureMin, StartStagePressureMax, PressureDifferenceErrorTimes);
                Log.Debug(log);
            }
        }

        #endregion

        #region 更新保持阶段信息

        private void UpdateHoldingStageInfo(string stage)
        {
            if (SelectTemplateModel is not null)
            {
                string stage_estimate_way = string.Empty;
                double stage_estime_value = 0;
                if (stage == "first")
                {
                    stage_estimate_way = SelectTemplateModel.FirstStageEstimateWay;
                    stage_estime_value = SelectTemplateModel.FirstStageEstimateValue;
                }
                else if (stage == "second")
                {
                    stage_estimate_way = SelectTemplateModel.SecondStageEstimateWay;
                    stage_estime_value = SelectTemplateModel.SecondStageEstimateValue;
                }
                else if (stage == "third")
                {
                    stage_estimate_way = SelectTemplateModel.ThirdStageEstimateWay;
                    stage_estime_value = SelectTemplateModel.ThirdStageEstimateValue;
                }
                else if (stage == "intensity")
                {
                    stage_estimate_way = SelectTemplateModel.IntensityStageEstimateWay;
                    stage_estime_value = SelectTemplateModel.IntensityStageEstimateValue;
                }
                else if (stage == "rigor")
                {
                    stage_estimate_way = SelectTemplateModel.RigorStageEstimateWay;
                    stage_estime_value = SelectTemplateModel.RigorStageEstimateValue;
                }

                if (stage_estimate_way == "固定数值")
                {
                    //HoldingStagePressureMin = HoldingStagePressure - stage_estime_value;
                    HoldingStagePressureMin = HoldingStagePressure;
                    HoldingStagePressureMax = HoldingStagePressure + stage_estime_value;
                    PressureDifference = stage_estime_value;
                }
                else
                {
                    HoldingStagePressureMax = Math.Round(HoldingStagePressure * (1 + (stage_estime_value / 100.0f)), 3);
                    //HoldingStagePressureMin = Math.Round(HoldingStagePressure * (1 - (stage_estime_value / 100.0f)), 3);
                    HoldingStagePressureMin = HoldingStagePressure;
                    PressureDifference = Math.Round(HoldingStagePressure * (stage_estime_value / 100.0f), 3);
                }
                PressureStandardLabel.Text = string.Format("{0}：{1}MPa-{2}MPa", StageString(CurrentStage), HoldingStagePressureMin,HoldingStagePressureMax);
                string log = string.Format("【{0}】保持基准：【{1}】【{2}-{3}】", StageString(CurrentStage), HoldingStagePressure, HoldingStagePressureMin, HoldingStagePressureMax);
                Log.Debug(log);
            }
        }

        #endregion

        #region 计时器方法
        /// <summary>
        /// 累计时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainTime(object? sender, System.Timers.ElapsedEventArgs e)
        {
            if (StartCollection)
            {
                TotalTime++;
                string time = Util.SecondToHMS(TotalTime);
                TotalTimeLabel.Text = time;
            }
            NowTime();
        }

        /// <summary>
        /// 采集状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CollecttionState(object? sender, System.Timers.ElapsedEventArgs e)
        {
            List<CollectionModel> collectList = collectionViewModel.CollectionList.Where(p => p.RegisterType =="DI" && p.Name =="近端设备").ToList();
            
            if (collectList.Count > 0)
            {
                CollectionModel model = collectList.First();
                foreach (DevicePointModel item in model.PointList)
                {
                    if (item.PointModel != null)
                    {
                        FormPointModel pointModel = item.PointModel;
                        bool[]? boolShorts = collectionViewModel.ReadBool(model);
                        if (boolShorts is not null)
                        {
                            EnableCollection = boolShorts[item.Address];
                            if (EnableCollection)
                            {
                                CollectStateTimer.Stop();
                                if (!StartCollection)
                                {
                                    ConfirmStart();
                                }
                                CollectionStateLabel.Text = "当前状态：可采集";
                                Log.Debug("可采集");
                            }
                            else
                            {
                                CollectionStateLabel.Text = "当前状态：未许可";
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReadRegister(object? sender, System.Timers.ElapsedEventArgs e)
        {
            if (StageList.Count == 0)
            {
                ConfirmStop();
            }
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            List<FormPointModel> list = FormPointModel.List(where);
            List<CollectionModel> collectList = collectionViewModel.CollectionList;
            Parallel.ForEach(collectList, model =>
            {
                if (model.RegisterType == "HR" || model.RegisterType == "IR")
                {
                    ushort[]? shorts = collectionViewModel.ReadUShort(model);
                    if (shorts is not null)
                    {

                        foreach (DevicePointModel item in model.PointList)
                        {
                            if (item.PointModel != null)
                            {
                                FormPointModel pointModel = item.PointModel;

                                if (pointModel.Enable == 1)
                                {
                                    double res = 0;
                                    string method = pointModel.Conver;
                                    string variable = pointModel.Variable;
                                    res = collectionViewModel.Invoke(method, item, shorts[item.Address]);
                                    if (!variable.IsNullOrEmpty())
                                    {
                                        FieldInfo? field = this.GetType().GetField(variable);
                                        if (field is not null)
                                        {
                                            field.SetValue(this, res);
                                        }
                                    }
                                    if (pointModel.FormControlName is not null)
                                    {
                                        if (pointModel.FormControlName.Length > 0)
                                        {

                                            AntdUI.Label? label = DataLabel(pointModel.FormControlName);
                                            if (label == null)
                                            {
                                                AntdUI.Battery? battery = Battery(pointModel.FormControlName);
                                                if (battery is not null)
                                                {
                                                    battery.Value = int.Parse(Math.Floor(res).ToString());
                                                }
                                                else
                                                {
                                                    Log.Error(string.Format("未找到【{0}】控件", pointModel.FormControlName));
                                                }
                                                return;
                                            }

                                            label.Text = res.ToString();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //Log.Info(string.Format("界面中未添加【{0}】点位", item.Name));
                            }
                        }
                    }
                }
            });
            UpdateCollectionDict();
            if (EnableBroadcastData)
            {
                if (Singleton.Instance.SetModel.BroadcastEnable == 1)
                {
                    string msg = string.Format("近端压力{0}兆帕，远端压力{1}兆帕", MainPressure, RemotePressure);
                    Broadcast.Broadcast(msg);
                }
                else
                {
                    Log.Error("未开启数据播报");
                }
                EnableBroadcastData = false;
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScottPlotAdd(object? sender, System.Timers.ElapsedEventArgs e)
        {
            var now = DateTime.Now;

            try
            {
                HistoryDataModel dataModel = new HistoryDataModel();
                dataModel.HistoryNumber = historyModel.Number;
                dataModel.MainPressure = MainPressure;
                dataModel.MainMediumTemperature = MainEnviromentTemperature;
                dataModel.MainBattery = MainBattery;
                dataModel.RemotePressure = RemotePressure;
                dataModel.RemoteMediumTemperature = RemoteMediumTemperature;
                dataModel.RemoteBattery = RemoteBattery;
                dataModel.Time = Util.Timestamp(now);
                int res = dataModel.Add();
                this.Invoke(new Action(() =>
                {
                    MPressureLogger.Add(now.ToOADate(), MainPressure);
                    RPressureLogger.Add(now.ToOADate(), RemotePressure);
                    MTemperatureLogger.Add(now.ToOADate(), MainEnviromentTemperature);
                }));
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateScottPlot(object? sender, System.Timers.ElapsedEventArgs e)
        {
            if (MPressureLogger.HasNewData)
            {
                this.Invoke(new Action(() =>
                {
                    FormsPlot1.Plot.Axes.AutoScale();

                    //FormsPlot1.Plot.Axes.AutoScaleY();
                    FormsPlot1.Refresh();
                    FormsPlot2.Refresh();
                }));
            }
        }
        /// <summary>
        /// 播报数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BroadcastData(object? sender, System.Timers.ElapsedEventArgs e)
        {
            if (!EnableBroadcastData)
            {
                EnableBroadcastData = true;
            }
        }

        #endregion

        #region 起步阶段
        private void CheckStartStage(object? sender, System.Timers.ElapsedEventArgs e)
        {
            string stageString = StageString(StageList[0]);
            string log = string.Empty;
            if ((MainPressure > StartStagePressureMax))
            {
                ReStartTimer();
                log = string.Format("当前压力【{0}】>【{1}】的标准", MainPressure, StartStagePressureMax);
                AlertMessage(log);
            }
            else if ((MainPressure < StartStagePressureMin))
            {
                ReStartTimer();
                log = string.Format("当前压力【{0}】<【{1}】的标准", MainPressure, StartStagePressureMin);
                AlertMessage(log);
            }
            else if ((MainPressure >= StartStagePressureMin) && (!StartStageHolding) && MainPressure > 0)
            {
                StartStageHolding = true;
                log = string.Format("【{0}】开始稳压【{1}】，范围：【{2}-{3}】", stageString, StartStagePressure, StartStagePressureMin, StartStagePressureMax);
                AlertMessage("数据采集中，请保持压力");
                CollectionStateLabel.Text = "当前状态：采集中";
            }
            if (log.Length > 0)
            {
                Log.Debug(log);
            }
            if (StartStageHolding)
            {
                if (StartStageTime == 0)
                {

                    if (PointList.Count == 0)
                    {
                        log = string.Format("【{0}】稳压通过。", stageString);
                        Log.Debug(log);
                    }
                    if (PointList.Count < SystemSetModelServices.HoldingPointCount)
                    {
                        PointList.Add(MainPressure);
                        log = string.Format("【{0}】采集点位数量：【{1}】", stageString, PointList.Count);
                        Log.Debug(log);
                    }
                    else
                    {
                        double sum = PointList.Sum();
                        PointList.Clear();
                        if (StageList.Count >= 1)
                        {
                            Broadcast.Broadcast(StageMessage);
                            StartStageTimer.Stop();
                            ReStartTimer();
                            StageTimer.Start();
                            HoldingStagePressure = Math.Round(sum / 10.0f, 3);
                            UpdateHoldingStageInfo(CurrentStage);
                            EnableHoldingStage = true;
                        }
                    }
                }
                else
                {
                    log = string.Format("【{0}】稳压剩余【{1}】s", stageString, StartStageTime);
                    Log.Debug(log);
                    if ((MainPressure >= StartStagePressureMin) && (MainPressure <= StartStagePressureMax))
                    {
                        StartStageTime--;
                    }
                }
            }
        }

        /// <summary>重置起步计时器
        /// 
        /// </summary>
        private void ReStartTimer()
        {
            StartStageHolding = false;
            StartStageTime = StartStageTimeInterval;
        }
        #endregion

        #region 保持阶段

        /// <summary> 当前阶段
        /// 
        /// </summary>
        private void CheckStage(object? sender, System.Timers.ElapsedEventArgs e)
        {
            if (StageTotalTime > 0)
            {
                StageTotalTime--;
                StageSurplusTimeString = Util.SecondToHMS(StageTotalTime);
                StageSurplusTimeLabel.Text = StageSurplusTimeString;
                if (MainPressure > HoldingStagePressureMax | MainPressure < HoldingStagePressureMin)
                {
                    HoldStagePressureErrorTimes++;
                    //Log.Error(string.Format("【{0}】,压力异常：【{1}】【{2}-{3}】【{4}次】", StageString(CurrentStage), MainPressure, HoldingStagePressureMin, HoldingStagePressureMax, HoldStagePressureErrorTimes));
                }
                else
                {
                    Log.Debug(string.Format("【{0}】：【{1}】保持剩余：【{2}】", StageString(CurrentStage), MainPressure, StageSurplusTimeString));
                    string msg = string.Format("{0}进行中，请保持压力", StageString(CurrentStage));
                    AlertMessage(msg);
                }

                //double difference = Math.Round((MainPressure - RemotePressure), 3);

                //if (difference > PressureDifference)
                //{
                //    HoldStagePressureDiffenceErrorTimes++;
                //    Log.Error(string.Format("【{0}】压差异常【{1}次】【主压力({2})-远压力({3}) = {4}】【标准{5}】", StageString(CurrentStage), HoldStagePressureDiffenceErrorTimes, MainPressure, RemotePressure, difference, PressureDifference));
                //}
            }
            else
            {
                StageTimer.Stop();
                string stage = CurrentStage;
                StageResult = true;
                string msg = string.Format("{0}完成，请注意安全", StageString(CurrentStage));
                Broadcast.Broadcast(msg);
                Thread.Sleep(300);
                if (stage == "first")
                {
                    UpdateCurrentStageResult("FirstStage", StageResult);
                }
                else if (stage == "second")
                {
                    UpdateCurrentStageResult("SecondStage", StageResult);
                }
                else if (stage == "third")
                {
                    UpdateCurrentStageResult("ThirdStage", StageResult);
                }
                else if (stage == "intensity")
                {
                    UpdateCurrentStageResult("IntensityStage", StageResult);
                }
                else if (stage == "rigor")
                {
                    UpdateCurrentStageResult("RigorStage", StageResult);
                }
                HoldStagePressureDiffenceErrorTimes = 0;
                HoldStagePressureErrorTimes = 0;
                if (StageList.Count > 1)
                {
                    StageList.RemoveAt(0);
                    UpdateStartStageInfo(StageList[0]);
                    StartStageTimer.Start();
                }
                else
                {
                    StageList.RemoveAt(0);
                    ConfirmStop();
                    Thread.Sleep(300);
                    msg = "工程试压完成，请注意安全";
                    Broadcast.Broadcast(msg);
                    AlertMessage(msg);
                    CollectionStateLabel.Text = "当前状态：未开始";
                }
                if (StageList.Count == 0)
                {
                    ConfirmStop();
                }
            }
        }

        #endregion
    }
}
